<script setup lang="ts">
import {ElMessage} from "element-plus";
import useCurrentInstance from "@/assets/ts/useCurrentInstance";
import {storeToRefs} from "pinia";
import appStore from "@/store";
import {VueCropper} from 'vue-cropper'
import {ref} from "vue";
import {Minus, Plus, RefreshLeft, RefreshRight} from "@element-plus/icons-vue";
import 'vue-cropper/dist/index.css'
import {uploadAvatar} from "@/http/m_api/user";
import {avatar_path_pre} from "@/assets/ts/constant";

const {userInfo} = storeToRefs(appStore.useUserInfoStore)

const props = defineProps({
  dialogVisibleCropper: {
    type: Boolean,
    default: false
  },
  option: {
    default: {}
  }
})

const cropper = ref<any>(null);

const emit = defineEmits(['update:dialogVisibleCropper', 'confirm']);

const defaultOption = {
  img: userInfo.value.avatar_url, // 裁剪图片的地址
  info: true, // 裁剪框的大小信息
  outputSize: 1, // 裁剪生成图片的质量
  canMove: true,
  outputType: "png", // 裁剪生成图片的格式
  canScale: true, // 图片是否允许滚轮缩放
  autoCrop: true, // 是否默认生成截图框
  canMoveBox: true, // 截图框能否拖动
  autoCropWidth: 200, // 默认生成截图框宽度
  autoCropHeight: 200, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  fixed: true, // 是否开启截图框宽高固定比例
  fixedNumber: [1, 1], // 截图框的宽高比例
  full: false, // 是否输出原图比例的截图
  original: false, // 上传图片按照原始比例渲染
  centerBox: true, // 截图框是否被限制在图片里面
  infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  border_radius: '50%'
}
const option = ref(Object.assign({}, defaultOption, props.option))

const previews = ref({
  url: ''
})
// 修改图片大小 正数为变大 负数变小
const changeScale = (num: number) => {
  num = num || 1
  cropper.value.changeScale(num)
}
// 向左边旋转90度
const rotateLeft = () => {
  cropper.value.rotateLeft()
}
// 向右边旋转90度
const rotateRight = () => {
  cropper.value.rotateRight()
}

// 上传图片处理
const beforeUpload = (rawFile: any) => {
  if (rawFile.type.indexOf('image/') == -1) {
    ElMessage.error('请上传图片类型文件!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  const reader = new FileReader()
  reader.readAsDataURL(rawFile)
  reader.onload = () => {
    option.value.img = reader.result
  }
}
// 实时预览事件
const realTime = (data: any) => {
  previews.value = data
}
// 关闭弹窗
const beforeClose = () => {
  option.value.img = ''
  previews.value.url = ''
  emit('update:dialogVisibleCropper', false)
}
// 提交图片
const determine = () => {
  cropper.value.endCrop()
  cropper.value.getCropBlob(async (data: any) => {
    let file_name = 'avatarPath.png'
    data.lastModifiedDate = new Date()
    data.name = file_name;
    let avatarFile = new File([data], file_name, {type: data.type, lastModified: Date.now()})
    let avatarUrl = URL.createObjectURL(data)
    emit('confirm', data, avatarFile, avatarUrl)
    return false;
  })
}

const showCropper = ref(true)


const openDialog = () => {
  showCropper.value = true
}


</script>

<template>
  <el-dialog
      width="800"
      style="border-radius: 5px"
      :model-value="dialogVisibleCropper"
      @opened="openDialog"
      :before-close="beforeClose"
  >
    <el-row>
      <el-col :span="12" style="height: 300px">
        <vue-cropper ref="cropper"
                     :img="option.img"
                     :output-size="option.outputSize"
                     :outputType="option.outputType"
                     :info="true"
                     :full="option.full"
                     :canMove="option.canMove"
                     :canMoveBox="option.canMoveBox"
                     :original="option.original"
                     :fixed="option.fixed"
                     :fixedNumber="option.fixedNumber"
                     :centerBox="option.centerBox"
                     :infoTrue="option.infoTrue"
                     :fixedBox="option.fixedBox"
                     :auto-crop="option.autoCrop"
                     :autoCropWidth="option.autoCropWidth"
                     :autoCropHeight="option.autoCropHeight"
                     @realTime="realTime"
                     v-if="showCropper"

        ></vue-cropper>
      </el-col>
      <el-col :span="12" style="height: 300px">
        <div class="preview-box"
             :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px', 'border-radius': option.border_radius}">
          <div :style="previews.div">
            <img :src="previews.url" :style="previews.img" alt="preview">
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row style="margin-top: 12px">
      <el-col :span="12">
        <el-row>
          <el-col :span="8">
            <el-upload
                action="#"
                :http-request="() => {}"
                :before-upload="beforeUpload"
                accept="image/*"
                :show-file-list="false"
            >
              <el-button>选择</el-button>
            </el-upload>
          </el-col>
          <el-col :span="4">
            <el-button :icon="Plus" @click="changeScale(1)">
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button :icon="Minus" @click="changeScale(-1)">
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button :icon="RefreshLeft" @click="rotateLeft()">
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button :icon="RefreshRight" @click="rotateRight()">
            </el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="4" :offset="8" style="margin-left: 22.3%">
        <el-button type="primary" @click="determine()">提 交</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<style scoped lang="scss">
.preview-box {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  overflow: hidden;
}
</style>